package org.jfk.sys.user;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.credential.DefaultPasswordService;
import org.apache.shiro.authc.credential.PasswordService;
import org.jfk.config.SystemConfig;
import org.jfk.core.controller.BaseController;
import org.jfk.core.utils.I18nUtil;
import org.jfk.sys.org.Org;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Record;

public class UserController extends BaseController {

	private static Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 给管理员用于修改用户属性
	 */
	public void edit() {
		User user = User.dao.findById(getParaToInt());
		if (user != null) {
			setAttr("user", user);
		}
		List<Map> orgList = Org.dao.findAll4Ztree();
		if (orgList != null && orgList.size()>0){
			String jsonOrgList = JsonKit.toJson(orgList);
			setAttr("orgList",jsonOrgList);
		}
		super.setBackUrl("");
	}	

	/**
	 * 给用自己修改个人属性
	 * 处理逻辑同edit，返回profile.jsp
	 * （是否可以考虑在edit上声明多个url，以处理类似情况）
	 */
	public void profile() {
		edit();
	}	

	public void update(){
		User user = getModel(User.class);
		user.update();
		super.renderJson();
	}	
	
	@Before(UserValidator.class)
	public void save() throws Exception {
		
		User user = getModel(User.class);
		if (user.get("id") == null){
			User currUser = super.getCurrUser();
			user.set("creator", currUser.getInt("id"));
			
			PasswordService ps = new DefaultPasswordService();
			String encrypted = ps.encryptPassword(SystemConfig.INIT_PASS);
			user.set("password", encrypted);
			user.save();
		}else{
			user.update();
		}
		super.renderJson();
	}	
	
	public void list(){
		listColumns = new String[][] { 
				{ "id", "编号" }, 
				{ "loginName", "登录名" },
				{ "realName", "真实姓名" }, 
				{ "orgName", "用户组" }, 
				{ "email", "电子邮箱" },
				{ "mobile", "手机号码" }, 
				{ "remark", "备注","0" }, 
				{ "picture", "头像","0" },
				{ "createTime", "创建时间" }, 
				{ "creator_loginName", "创建人" },
				{ "status_dict_value", "数据状态" },
				{ "status", "状态","0" } 
				};
		
		super.setAttrs();
		
		setAttr("page",User.dao.paginate(this));
		
		List<Map> orgList = Org.dao.findAll4Ztree();
		if (orgList != null && orgList.size()>0){
			String jsonOrgList = JsonKit.toJson(orgList);
			setAttr("orgList",jsonOrgList);
		}		
	}



	public void del() {
		String id = getPara("id");
		User.dao.deleteById(id);
		super.renderText("test del");
	}

	
	public void delAll() {
		Integer[] checkedId = super.getParaValuesToInt("id[]");

		for (int i = 0; checkedId != null && i < checkedId.length; i++) {
			User.dao.deleteById(checkedId[i]);
		}
		super.renderText("test delAll");
	}
	
	/**
	 * 密码初始化
	 */
	public void initPassword(){
		int userId = super.getParaToInt("userId");
		User user = User.dao.findById(userId);	
		PasswordService ps = new DefaultPasswordService();
		String encrypted = ps.encryptPassword(SystemConfig.INIT_PASS);
		user.set("password", encrypted);
		user.update();
		resultJson = new HashMap();
		resultJson.put("errorCode", 0);
		resultJson.put("errorMsg", I18nUtil.getValueByKey("admin.common.errorMsg.success"));
		
		super.renderJson(resultJson);
	}
	
	/**
	 * 修改密码
	 */
	public void modifyPassword() {
		String oldPwd = super.getPara("old_password");
		String newPwd = super.getPara("new_password");
		User user = getModel(User.class);
		
		user = user.dao.findById(user.getInt("id"));
		
		String encrypted = user.getStr("password");
		PasswordService ps = new DefaultPasswordService();
		resultJson = new HashMap();
		if (ps.passwordsMatch(oldPwd, encrypted)){
			String newEncrypted = ps.encryptPassword(newPwd);
			user.set("password", newEncrypted).update();
			resultJson.put("errorCode", 0);
			resultJson.put("errorMsg", I18nUtil.getValueByKey("admin.common.errorMsg.success"));
		}else{
			resultJson.put("errorCode", 1);
			resultJson.put("errorMsg", I18nUtil.getValueByKey("admin.common.errorMsg.fail.user.1"));
		}
		super.renderJson(resultJson);
	}
	
	public void ajaxLoadUserByRole(){
		int roleId = this.getParaToInt(0,-1);
		List<Record> list = User.dao.getUsersByRole(roleId);
		this.renderJson(list);
	}
}
